<?php
/**
 * User: b179a9
 * Date: 10/10/11
 * Time: 7:37 PM
 */

class ReportController extends Zend_Controller_Action
{

    const RECORDS_PER_PAGE = 100000;

    /**
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    public function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('pirates-layout');
        }

        $this->_flashMessenger = new Lib_Flash();
        $auth = Zend_Auth::getInstance();
        $data = $auth->getStorage()->read();
        $massiv = (array)$data;
        if (isset($massiv['name'])) $this->view->name = $massiv['name'];
    }

    public function __call($name, $args)
    {
        $this->_forward('index');
    }

    public function indexAction()
    {
        $mapsManager = new \Managers\Map();

        $page = intval($this->_request->getParam('page', 1));
        
        $offset = $page > 0 ? ($page - 1) * self::RECORDS_PER_PAGE : 0;

        $filter = array('dateStart' => array('dateend' => date('Y-m-d')),
                        'order' => array('id' => 'desc'),
                        'start' => $offset,
                        'limit' => self::RECORDS_PER_PAGE);
        $maps = $mapsManager->getList($filter);
                
        $total = $mapsManager->getTotal($filter);
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($total));
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage(self::RECORDS_PER_PAGE);

        $this->view->maps = $maps;
        $this->view->paginator = $paginator;
    }

    public function viewAction()
    {
        $id = $this->_request->getParam('id');
        $mapsManager = new \Managers\Map();

        if ($mapsManager->isAvailable($id)) {
            $this->_flashMessenger->addMessage('This map is not available for view results.', Lib_Flash::ERROR, Lib_Flash::PRE);
            $this->_redirect('/report');
        }

        $map = $mapsManager->getById($id);

        $answersManager = new \Managers\Answers();
        $filter = array('map' => $id);
        $answers = $answersManager->getList($filter);

        $this->view->map = $map;
        $this->view->answers = $answers;

    }

}
